<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="categoryName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search"
                style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="categoryOptions" :props="defaultProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" node-key="categoryId" default-expand-all highlight-current
                @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
              label-width="68px">
              <el-form-item label="货品名称" prop="productName">
                <el-input v-model="queryParams.productName" placeholder="请输入货品名称" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="分类名称" prop="categoryName">
                <el-input v-model="queryParams.categoryName" placeholder="请输入分类名称" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                  <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  v-hasPermi="['storage:product:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                  v-hasPermi="['storage:product:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                  @click="handleDelete" v-hasPermi="['storage:product:remove']">删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                  v-hasPermi="['storage:product:export']">导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="货品名称" align="center" prop="productName" />
              <el-table-column label="分类名称" align="center" prop="categoryName" />
              <el-table-column label="计量单位" align="center" prop="unit" />
              <el-table-column label="货品条码" align="center" prop="barcode" />
              <el-table-column label="库存数量" align="center" prop="stockQuantity" />
              <el-table-column label="进价" align="center" prop="purchasePrice" />
              <el-table-column label="售价" align="center" prop="sellingPrice" />
              <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="保质期" align="center" prop="expirationDate" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="修改人" align="center" prop="updateBy" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['storage:product:edit']">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                    v-hasPermi="['storage:product:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 添加或修改货品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="货品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入货品名称" />
        </el-form-item>
        <el-form-item label="货品分类" prop="categoryId">
          <treeselect v-model="form.categoryId" :options="enabledCategoryOptions" :normalizer="normalizeOptions"
            :show-count="true" placeholder="请选择货品分类" />
        </el-form-item>
        <!-- <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item> -->
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入计量单位" />
        </el-form-item>
        <el-form-item label="货品条码" prop="barcode">
          <el-input v-model="form.barcode" placeholder="请输入货品条码" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="进价" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入进价" />
        </el-form-item>
        <el-form-item label="售价" prop="sellingPrice">
          <el-input v-model="form.sellingPrice" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker clearable v-model="form.productionDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择生产日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="保质期" prop="expirationDate">
          <el-date-picker clearable v-model="form.expirationDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择保质期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/storage/product"
import { categoryTree } from "@/api/storage/category"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"

export default {
  name: "Product",
  dicts: ['sys_normal_disable'],
  components: { Treeselect, Splitpanes, Pane },
  data() {
    return {
      selId: '',
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      // 所有分类树选项
      categoryOptions: undefined,
      // 过滤掉已禁用分类树选项
      enabledCategoryOptions: undefined,
      // 分类名称
      categoryName: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 货品信息表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        categoryName: null,
        categoryId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "货品名称不能为空", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "计量单位不能为空", trigger: "blur" }
        ],
        barcode: [
          { required: true, message: "货品条码不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" }
        ],
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    categoryName(val) {
      console.log(val)
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getCategoryTree()
  },
  methods: {
    /** 查询分类下拉树结构 */
    getCategoryTree() {
      categoryTree().then(response => {
        this.categoryOptions = response.data
        console.log(response.data)
        this.enabledCategoryOptions = this.filterDisabledCategory(JSON.parse(JSON.stringify(response.data)))
        console.log(JSON.stringify(this.enabledCategoryOptions))
      })
    },
    // 过滤禁用的分类
    filterDisabledCategory(categoryList) {
      console.log(categoryList);
      return categoryList.filter(category => {
        console.log("category.status");
        console.log(category.status);
        console.log(category);
        if (category.status == "1") {
          return false
        }
        if (category.children && category.children.length) {
          category.children = this.filterDisabledCategory(category.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {

      if (!value) return true
      return data.categoryName.indexOf(value) !== -1
    },
    normalizeOptions(node) {
      // node: 原始的选项数据
      // 在这里根据需要进行选项数据的规范化操作，并返回规范化后的选项数据
      // 例如，可以将原始的选项数据转换为符合插件要求的结构
      if (node.children && !node.children.length) {
        // 去掉children=[]的children属性
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      };
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log(JSON.stringify(data))
      console.log(JSON.stringify(data.categoryId))
      this.queryParams.categoryId = data.categoryId
      this.getList()
    },
    /** 查询货品信息列表 */
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        categoryId: this.queryParams.categoryId ? this.queryParams.categoryId : null,
        productName: null,
        categoryName: null,
        unit: null,
        barcode: null,
        imageUrl: null,
        stockQuantity: null,
        purchasePrice: null,
        sellingPrice: null,
        productionDate: null,
        expirationDate: null,
        status: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        createUserId: null,
        updateUserId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加货品信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改货品信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids
      this.$modal.confirm('是否确认删除货品信息编号为"' + productIds + '"的数据项？').then(function () {
        return delProduct(productIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
